<template>
  <div class="box">
    <h3>借款资料</h3>
      <el-row :gutter="40">
        <el-col :span="11">
          <el-form :model="ruleForm" label-width="135px" ref="ruleForm">
            <el-form-item label="上传借款材料："> 
              <el-upload
                :action="imageUploadPath"
                list-type="picture-card"
                :file-list="imageList"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                multiple
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="" />
              </el-dialog>
            </el-form-item>
          </el-form>
        </el-col>

        <el-col :span="11">
          <el-form label-width="135px">
          </el-form>
        </el-col>
      </el-row>
  </div>
</template>

<script>
export default {
  props: {
    formData: {
      type: Object,
      default() {
        return {}
      }
    },
    imageUploadPath: {
      type: String,
      default: "http://172.17.2.238:8080/oss/service/file/upload"
    }
  },
   data() {
      
      return {
        ruleForm: this.getInitRoleForm(),
        dialogImageUrl: '',
        dialogVisible: false,
        imageList: []
      };
    },
    methods: {
      handleRemove(file, fileList) {
        this.imageList = fileList.map( item => ({name: "",url: item.url}))
      },
      handleSuccess(res){
        if(res.code == 20000) {
          this.imageList.push({
            name: "",
            url: res.data.fileUrl
          });
        } else {
          this.$message.error("图片上传失败！")
        }
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      initImageList() {
        this.imageList = !this.ruleForm.loanInformation.length ? [] :
          this.ruleForm.loanInformation.split(",").map( item => ({
            name: "",
            url: item
          }));
      }
    },
    watch: {
       imageList(newVal) {
         this.ruleForm.loanInformation = newVal.map( item => item.url).join(",");
       },
      formData() {
        this.ruleForm = this.getInitRoleForm();
        this.initImageList();
      }
    },
    beforeCreate() {
      const defaultData = {
        loanInformation: ""
      };
      
      this.getInitRoleForm = function () {
        if(this._.isEmpty(this.formData)) return defaultData;
        let obj = {}, formCopy = this._.cloneDeep(this.formData);
        for(let key in defaultData) {
          obj[key] = formCopy[key]
        }
        return obj;
      }
    },
    created() {
     this.initImageList();
    }
}
</script>

<style scoped>
.box {
  width: 1100px;

}
</style>